import { Injectable,Query,Req } from '@nestjs/common';
import { User } from './entities/user.entity';
import { SysUserWithRoleEntity } from './entities/user.role.entity';
import { InjectRepository} from '@nestjs/typeorm';
import { Repository,In, Not } from 'typeorm';
import {CreateUserDto,ListUserDto,UpdateUserDto} from './dto/index';
import { v4 as uuidv4 } from 'uuid';
import {ResultData} from '../../../common/utils/result';
import { makeSalt, encryptPassword } from '../../../common/utils/crypto';
// import {UuidService} from '../../../uuid/uuid.service';
@Injectable()
export class UserService {

    constructor(
        @InjectRepository(User)
        private usersRepository: Repository<User>,
        @InjectRepository(SysUserWithRoleEntity)
        private readonly sysUserWithRoleEntityRep: Repository<SysUserWithRoleEntity>,
      ) {}
      
      // 定义方法供路由调用
      async find() {
        const res = await this.usersRepository.find();
        return ResultData.ok(res);
      }

      async findPage(@Query() query: ListUserDto,@Req() req) {
          const entity = this.usersRepository.createQueryBuilder('sys_user');
          if (query.pageSize && query.pageNum) {
            entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
          }
          const [list, total] = await entity.getManyAndCount();
          const data =  {
            total:total,
            data:list,
          }
          return ResultData.ok(data);
      }

      async findOne(userid:string) {
        const data =  await this.usersRepository.findOne({
            where:{
              userid:userid
            }
        })
        return ResultData.ok(data);
        // return this.usersRepository.findOne({
        //   where:{
        //     userid:userid
        //   }
        // })
      }
    
      // 定义方法供路由调用
      async add(user: CreateUserDto) {
        user.create_time = new Date().toLocaleString();
        const salt = "init"
        user.password = encryptPassword("123456", salt);
        user.userid = uuidv4();
        const res = await this.usersRepository.insert(user)
        return ResultData.ok({
          code:200,
          Msg:"添加成功",
          data:null
        });
      }
    
      // 定义方法供路由调用
      async update(user: UpdateUserDto) {
        user.update_time = new Date().toLocaleString();
        const res = await this.usersRepository.update({ userid: user.userid }, user) 
        return ResultData.ok(res);
      }
    
      // 定义方法供路由调用
      async remove(ids:string[]) {
        const res = await this.usersRepository.update(
          { userid: In(ids)},
          {
            status: '2',//禁用
          },
        )
        return ResultData.ok(res);
      }

      updateStatus(id:string,status:string) {
        const res = this.usersRepository.update(
          { userid:id },
          { status:status }
        );
        return ResultData.ok(res);
      }

      async addRole(userid:string,roleids:string[]) {
        const roleInfo = await this.sysUserWithRoleEntityRep.find({
          where:{userid:userid}
        });
        if(roleInfo.length==0){
          roleids.map(async item=>{
              await this.sysUserWithRoleEntityRep.insert({
                userid: userid,
                roleid: item
              })
          })
        }else{
          await this.sysUserWithRoleEntityRep.delete({
            userid: userid,
          });
          roleids.map(async item=>{
              await this.sysUserWithRoleEntityRep.insert({
                userid: userid,
                roleid: item
              })
          })
        }
        return ResultData.ok();
        
      }

     
}
